import React, { useRef, useCallback, useMemo, useEffect } from 'react';
import { connect } from 'umi';
import { Form, Spin } from 'antd';
import classNames from 'classnames';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import PageRouter from '@/components/PageRouter/PageRouter';
import OrganizationSelect from '@/components/OrganizationSelect';

import modelType from '@/pages/SalaryManage/constant/commonModelType';
import SearchWrapper from '@/pages/SalaryManage/Statistics/component/SearchWrapper';
import TableWrapper from '@/pages/SalaryManage/Statistics/component/TableWrapper';
import StatisticsMenuFilter from '@/pages/SalaryManage/Statistics/component/StatisticsMenuFilter';
import StatisticsRouter from '@/pages/SalaryManage/Statistics/component/StatisticsRouter';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

const statisticsFactory = ({ namespace, isMoreExportType = false }) => {
    const DISPATCH_TYPE = {
        initType: `${namespace}/${modelType.E_INIT}`,
        searchType: `${namespace}/${modelType.E_SEARCH}`,
        setSearchCondition: `${namespace}/${modelType.SET_SEARCH_CONDITION}`,
        tablePageChangeType: `${namespace}/${modelType.E_TABLE_PAGE_CHANGE}`,
        excelExportType: `${namespace}/${modelType.E_EXCEL_EXPORT}`,
        setMultiStoreType: `${namespace}/${modelType.SET_MULTI_STORE}`
    };

    const SearchWrapperConnect = connect(({ [namespace]: model }) => ({
        searchModel: model.searchModel,
        DISPATCH_TYPE
    }))(SearchWrapper);

    /**
     * 表格控件
     * @param columns
     * @param dataSource
     * @param tablePageChange
     * @param pagination
     * @returns {JSX.Element}
     * @constructor
     */
    const TableWrapperConnect = connect(({ [namespace]: model }) => {
        const { tableHeader, dataSource, pagination, columnsRender, dataSourceRender, summaryFieldsRender } = model;

        const renderColumns = columnsRender ? columnsRender(tableHeader) : tableHeader;
        const renderDataSource = dataSourceRender ? dataSourceRender(dataSource) : dataSource;
        const renderSummaryFields = summaryFieldsRender ? summaryFieldsRender(renderColumns) : [];

        return {
            columns: renderColumns,
            dataSource: renderDataSource,
            summaryFields: renderSummaryFields,
            pagination,
            DISPATCH_TYPE
        };
    })(TableWrapper);

    const getYearByMoment = momentInstance => (momentInstance ? +momentInstance.format('YYYY') : null);
    const getMonthByMoment = momentInstance => (momentInstance ? +momentInstance.format('M') : null);

    let StatisticsPage = ({
        pageLoading,
        title,
        subTitle,
        selectOrganizationCode,
        organizationResponse,
        countryNameCode,
        dispatch
    }) => {
        useEffect(() => {
            if (selectOrganizationCode) {
                dispatch({
                    type: DISPATCH_TYPE.initType,
                    payload: {
                        organizationCode: selectOrganizationCode
                    }
                });
            }
        }, [selectOrganizationCode]);

        const formRef = useRef(null);

        const generateSearchModel = useCallback(
            allValues => {
                const { v_entryDate, ...searchModel } = allValues;
                const { period } = searchModel;

                if (period?.[0]) {
                    searchModel.startYear = getYearByMoment(period?.[0]);
                    searchModel.startMonth = getMonthByMoment(period?.[0]);
                } else {
                    searchModel.startYear = null;
                    searchModel.startMonth = null;
                }

                if (period?.[1]) {
                    searchModel.endYear = getYearByMoment(period?.[1]);
                    searchModel.endMonth = getMonthByMoment(period?.[1]);
                } else {
                    searchModel.endYear = null;
                    searchModel.endMonth = null;
                }

                if (v_entryDate?.[0]) {
                    searchModel.startEntryDate = v_entryDate?.[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
                } else {
                    searchModel.startEntryDate = null;
                }

                if (v_entryDate?.[1]) {
                    searchModel.endEntryDate = v_entryDate?.[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
                } else {
                    searchModel.endEntryDate = null;
                }

                searchModel.organizationCode = selectOrganizationCode;
                return searchModel;
            },
            [selectOrganizationCode]
        );

        const onSearch = useCallback(() => {
            dispatch({
                type: DISPATCH_TYPE.searchType
                // payload: searchModel
            });
        }, []);

        const updateSearchModel = useCallback(
            allValues => {
                const searchModel = generateSearchModel(allValues);
                dispatch({
                    type: DISPATCH_TYPE.setSearchCondition,
                    payload: searchModel
                });
            },
            [generateSearchModel]
        );

        const EnhancedSearchWrapper = useMemo(
            () =>
                Form.create({
                    // 值变更时不立即收索
                    onValuesChange: (props, changedValues, allValues) => {
                        updateSearchModel(allValues);
                    }
                })(SearchWrapperConnect),
            [updateSearchModel]
        );

        const handleOrganizationChange = useCallback(
            value => {
                if (selectOrganizationCode !== value) {
                    dispatch({
                        type: 'statisticsModel/setMultiStore',
                        payload: {
                            selectOrganizationCode: value,
                            countryNameCode: null
                        }
                    });
                }
            },
            [selectOrganizationCode]
        );

        return (
            <StatisticsRouter
                type="salaryDirectory"
                countryNameCode={countryNameCode}
                extraButton={
                    <div style={{ display: 'flex' }}>
                        <OrganizationSelect
                            isStrictly
                            isNeedPermission
                            style={{ width: 220 }}
                            onChange={handleOrganizationChange}
                            value={selectOrganizationCode}
                            allowClear={false}
                            dropdownMatchSelectWidth
                            treeDataFromProp
                            treeDataList={organizationResponse}
                        />
                    </div>
                }
            >
                <div className={salaryStyle.salaryWrapper}>
                    <EnhancedSearchWrapper
                        onSearch={onSearch}
                        generateSearchModel={generateSearchModel}
                        wrappedFormRef={form => {
                            formRef.current = form;
                        }}
                        organizationCode={selectOrganizationCode}
                        isMoreExportType={isMoreExportType}
                    />
                    <Spin spinning={pageLoading}>
                        <div className={classNames(salaryStyle.textCenter, salaryStyle.mb32)}>
                            <div className={classNames(salaryStyle.fontBig, salaryStyle.bold)}>{title}</div>
                            <div className={salaryStyle.s}>{subTitle}</div>
                        </div>
                        <TableWrapperConnect />
                    </Spin>
                </div>
            </StatisticsRouter>
        );
    };
    StatisticsPage = connect(({ [namespace]: model, statisticsModel }) => ({
        pageLoading: model.pageLoading,
        title: model.title,
        subTitle: model.subTitle,
        selectOrganizationCode: statisticsModel.selectOrganizationCode,
        organizationResponse: statisticsModel.organizationResponse
    }))(StatisticsPage);

    const StatisticsPageWrapper = () => (
        <PageHeaderWrapper type="success">
            <StatisticsMenuFilter>
                <StatisticsPage />
            </StatisticsMenuFilter>
        </PageHeaderWrapper>
    );

    return {
        DISPATCH_TYPE,
        SearchWrapperConnect,
        TableWrapperConnect,
        StatisticsPage,
        StatisticsPageWrapper
    };
};

export default statisticsFactory;
